package com.gimi.cloud.bbp.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.bbp.common.constant.RedisKeyConstant;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.MD5;
import com.gimi.cloud.bbp.common.utils.ReflectUtils;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.commonService.redis.RedisService;
import com.gimi.cloud.bbp.dto.params.LoginParams;
import com.gimi.cloud.bbp.dto.sys.SysMasterDTO;
import com.gimi.cloud.bbp.manage.service.log.LogMasterLoginService;
import com.gimi.cloud.bbp.manage.service.sys.SysMasterService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录相关Controller
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2017-12-20
 **/
@RestController
public class LoginController {
    private static  final Logger logger = LoggerFactory.getLogger(LoginController.class);
    private RedisService redisService;
    private SysMasterService sysMasterService;
    private LogMasterLoginService logMasterLoginService;

    @Autowired
    public LoginController(RedisService redisService, SysMasterService sysMasterService, LogMasterLoginService logMasterLoginService) {
        this.redisService = redisService;
        this.sysMasterService = sysMasterService;
        this.logMasterLoginService = logMasterLoginService;
    }

    /**
     * 登录
     * @param request
     * @param response
     * @param param 登录参数
     * @throws Exception
     */
    @PostMapping("/login")
    public Response login(HttpServletRequest request, HttpServletResponse response, @RequestBody LoginParams param) throws Exception{
        //获取redis中的验证码
        String validateCode = redisService.get(RedisKeyConstant.PUBLIC_VALIDATE_CODE_PREFIX+param.getValidateKey());
        Response resp = new Response();
        if(StringUtils.isBlank(validateCode)){
            resp.setResponseCode(ResponseCodeEnum.SIGNATURE_ERROR,"验证码已失效，请重新获取");
            return resp;
        }
        if(!validateCode.equalsIgnoreCase(param.getValidateCode())){
            resp.setResponseCode(ResponseCodeEnum.SIGNATURE_ERROR,"验证码错误");
            return resp;
        }
        //根据登录名获取管理员信息
        SysMasterDTO sysMasterDTO = sysMasterService.queryMasterByUsername(null,param.getUsername());
        //账户不存在
        if(null == sysMasterDTO){
            resp.setResponseCode(ResponseCodeEnum.UNKNOWN_ERROR);
            return resp;
        }
        if(!sysMasterDTO.getPassword().equals(MD5.toMD5(param.getPassword()))){
            resp.setResponseCode(ResponseCodeEnum.SIGNATURE_ERROR,"用户名密码不匹配");
            return resp;
        }
        //判断用户锁定状态
        if(null == sysMasterDTO.getMaIsLock() || sysMasterDTO.getMaIsLock() == 1){
            resp.setResponseCode(ResponseCodeEnum.ERR_MASTER_IS_LOCKED);
            return resp;
        }
        //判断用户启用禁用状态
        if(null == sysMasterDTO.getMaState() || 1 != sysMasterDTO.getMaState()){
            resp.setResponseCode(ResponseCodeEnum.ERR_MASTER_STATE);
            return resp;
        }
        //生成token，并存储在redis中
        String token = sysMasterService.createTokenAndSet2Redis(sysMasterDTO);
        if(StringUtil.isBlank(token)){
            resp.setResponseCode(ResponseCodeEnum.ERROR_SYSTEM_CONFNIG,"生成登录Token异常");
            return resp;
        }
        //将用户token添加至redis缓存
        redisService.setObject(RedisKeyConstant.MANAGE_LOGIN_MASTER_PREFIX+ sysMasterDTO.getMaId(),sysMasterDTO);
        //获取用户权限信息
        Map<String,Object> permission = sysMasterService.getMasterPermissions(sysMasterDTO,sysMasterDTO.getMaId());
        //重新添加值redis缓存
        redisService.setObject(RedisKeyConstant.MANAGE_LOGIN_MASTER_PERMISSION_PREFIX+sysMasterDTO.getMaId(),permission);
        Map<String,Object> resData = new HashMap<>();
        resData.put("master", sysMasterDTO);
        resData.put("token",token);
        resData.put("permission",permission);
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(param,sysMasterDTO);
        logMasterLoginService.saveMasterLoginLog(sysMasterDTO,true);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED,"登录成功");
        resp.setRes_data(resData);
        return resp;
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @param masterDTO 登录参数
     * @throws Exception
     */
    @PostMapping("/logout")
    public Response logout(HttpServletRequest request, HttpServletResponse response, @RequestBody SysMasterDTO masterDTO) throws Exception{
        masterDTO.setUsername(masterDTO.getUname());
        Response resp = new Response();
        JSONObject masterTokenRule = redisService.getJSONObjectConfigByKey(RedisKeyConstant.CONFIG_KEY_MANAGE_USER_TOKEN_RULE);
        if(null == masterTokenRule){
            resp.setResponseCode(ResponseCodeEnum.NO_DATA,"未获取到系统配置参数");
            return resp;
        }
        String isSingleLogin = masterTokenRule.getString("is_single_login");
        //如果当前为单一登录，直接把redis中的登录信息移除掉
        if("1".equals(isSingleLogin)){
            //移除登录用户前缀
            redisService.del(RedisKeyConstant.MANAGE_LOGIN_MASTER_TOKEN_PREFIX +masterDTO.getUsername());
            redisService.del(RedisKeyConstant.MANAGE_LOGIN_MASTER_PREFIX+masterDTO.getUid());
        }else{
            //如果当前非单一登录
            //获取用户当前的token信息
            List<String> userTokens = redisService.getList(RedisKeyConstant.MANAGE_LOGIN_MASTER_TOKEN_PREFIX +masterDTO.getUsername(),String.class);
            if(null != userTokens){
                //移除当前请求token
                userTokens.remove(masterDTO.getAuthToken());
                if(userTokens.size() >0){
                    //更新当前用户的token信息
                    redisService.set(RedisKeyConstant.MANAGE_LOGIN_MASTER_TOKEN_PREFIX +masterDTO.getUsername(),JsonUtil.toJson(userTokens),masterTokenRule.getLong("validate_times"), TimeUnit.SECONDS);
                }
            }

        }
        SysMasterDTO sysMasterDTO = sysMasterService.load(masterDTO,masterDTO.getUid());
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(masterDTO,sysMasterDTO);
        logMasterLoginService.saveMasterLoginLog(sysMasterDTO,false);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED,"注销成功");
        return resp;
    }
}
